<template>
    <div class="form-design">
        <!-- <v-form-designer></v-form-designer> -->
        <VFormDesigner ref="formDesigner" :ruleForm="ruleForm" @handleRuleFrom="handleRuleFrom">
            <template #customToolButtons>
                <el-button @click="saveForm" size="small" type="primary" :icon="Plus">保存</el-button>
            </template>
        </VFormDesigner>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import VFormDesigner from '@/components/form-designer/index.vue';
import { getDetail } from '@/api/crf/crf.js';
import { add } from '@/api/crf/crf.js';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const form = ref({
    name: '',
    lbType: '',
    content: '',
});
const ruleForm = ref({});
const formDesigner = ref(null);
const route = useRoute();
const id = ref('')
ruleForm.value = route.query;
const handleRuleFrom = ruleForm => {

    form.value.lbType = ruleForm.lbType;
    form.value.name = ruleForm.name;
};

const saveForm = async () => {


    if (!form.value.lbType) {
        ElMessage.error('请选择量表类型');
        return;
    }
    if (!form.value.name) {
        ElMessage.error('请填写表名');
        return;
    }
    if (id.value) {
        getDetailData(id.value);
        form.value.id = id.value;
    } else {
        Object.assign(form.value, route.query);
    }
    form.value.content = JSON.stringify(formDesigner.value.getFormJson());

    if (form.value.shareType == '3') {
        form.value.shareType = null;
    }
    console.log(form.value, formDesigner.value.getFormJson());

    let res = await add(form.value);

    id.value = res.data.data;
    ElMessage.success('保存成功');
};

const getDetailData = async (id) => {
    const { data: res } = await getDetail(id);

    if (res.code == 200) {
        formDesigner.value.setFormJson(JSON.parse(res.data.content));
        ruleForm.value = res.data;
    }
};
onMounted(() => {
    if (route.query.id) {
        getDetailData(route.query.id);
    } else {
        console.log(22);

        formDesigner.value.clearDesigner();
    }
});
</script>

<style lang="css" scoped>
.form-design {
    height: 100%;
    width: 100%;
}
</style>
